import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsResult.dart';

// import 'package:ichinesereader/pages/assessment/assessmentQuestionReview.dart';
// import 'package:ichinesereader/pages/teacher/questionReview.dart';
import 'package:ichinesereader/pages/teacher/evaluationRecordReview.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';

// ignore: must_be_immutable
class AssessmentBooksDataGrids extends StatelessWidget {
  AssessmentBooksDataGrids(this.quizbookItems, this.isTeacher);

  List<QuestionRecord> quizbookItems;
  bool isTeacher = false;

  bool isWebOrDesktop =
      GetPlatform.isMacOS || GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build assessment/quiz books DataGrids');
    return Column(children: [
      // isTeacher
      //     ? Row(
      //         children: [
      //           ElevatedButton(
      //               child: Text('Selected'.tr),
      //               onPressed: () {
      //                 if (this._dataGridController.selectedRows.length > 0) {
      //                   var _selectedRow =
      //                       this._dataGridController.selectedRows[0];
      //                   var cc = _selectedRow
      //                       .getCells()
      //                       .where((element) => element.columnName == 'Id')
      //                       .first
      //                       .value;

      //                   Get.snackbar(
      //                       'Message'.tr,
      //                       quizbookItems
      //                           .where((element) => element.id == cc)
      //                           .first
      //                           .questionGroup!
      //                           .title
      //                           .toString());
      //                 }
      //               }),
      //           SizedBox(width: 20),
      //           ElevatedButton(
      //               child: Text('Selected'.tr),
      //               onPressed: () {
      //                 if (this._dataGridController.selectedRows.length > 0) {
      //                   var _selectedRow =
      //                       this._dataGridController.selectedRows[0];
      //                   var cc = _selectedRow
      //                       .getCells()
      //                       .where((element) => element.columnName == 'Id')
      //                       .first
      //                       .value;
      //                   Get.snackbar(
      //                       'Message'.tr,
      //                       quizbookItems
      //                           .where((element) => element.id == cc)
      //                           .first
      //                           .questionGroup!
      //                           .title
      //                           .toString());
      //                   quizbookItems
      //                       .removeWhere((element) => element.id == cc);
      //                   // Get.snackbar('test',
      //                   //     assesssmentItems.where((element) => element.assessmentId==cc).first.name.toString());
      //                 }
      //               }),
      //         ],
      //       )
      //     : Text(''),
      Expanded(child: _buildDataGrid()),
    ]);
  }

  SfDataGrid _buildDataGrid() {
    return SfDataGrid(
      source: QuizbookDataGridSource(items: quizbookItems),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      controller: _dataGridController,
      showCheckboxColumn: isTeacher ? true : false,
      checkboxColumnSettings: Get.isDarkMode
          ? DataGridCheckboxColumnSettings(
              backgroundColor: Color(0xff0a0e21),
            )
          : DataGridCheckboxColumnSettings(backgroundColor: Colors.blue[50]),
      allowSorting: true,
      allowTriStateSorting: true,
      allowFiltering: true,
      allowSwiping: isTeacher ? true : false,
      selectionMode: SelectionMode.single,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {},
            child: Container(
                color: Colors.redAccent,
                child: Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          width: isWebOrDesktop ? 280 : 260,
          columnName: 'Title',
          label: buildDataGridColumnLabel('Title'),
        ),
        GridColumn(
          columnName: 'Type',
          width: isWebOrDesktop ? 150 : 150,
          label: buildDataGridColumnLabel('Type'),
        ),
        GridColumn(
          width: isWebOrDesktop ? 160 : 160,
          columnName: 'Username',
          visible: isTeacher ? true : false,
          label: buildDataGridColumnLabel('UserName'),
        ),
        GridColumn(
          columnName: 'Text',
          allowFiltering: false,
          width: isWebOrDesktop ? 150.0 : 120.0,
          label: buildDataGridColumnLabel('Text'),
        ),
        GridColumn(
          columnName: 'Audio',
          allowFiltering: false,
          width: isWebOrDesktop ? 150.0 : 120.0,
          label: buildDataGridColumnLabel('Audio'),
        ),
        GridColumn(
          columnName: 'Status',
          allowFiltering: false,
          width: isWebOrDesktop ? 160 : 120,
          label: buildDataGridColumnLabel('Status'),
        ),
        GridColumn(
          columnName: 'LastUpdated',
          allowFiltering: false,
          width: 180,
          label: buildDataGridColumnLabel('LastUpdated'),
        ),
        GridColumn(
          columnName: 'Id',
          allowFiltering: false,
          width: 5,
          visible: false,
          label: buildDataGridColumnLabel('Id'),
        ),
      ],
    );
  }
}

class QuizbookDataGridSource extends DataGridSource {
  QuizbookDataGridSource({required List<QuestionRecord> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Title',
                  value: dataGridRow.questionGroup?.title ?? 'No Title'),
              DataGridCell<String>(
                  columnName: 'Type', value: dataGridRow.type ?? 'No Type'),
              DataGridCell<String>(
                  columnName: 'Username', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'Text', value: dataGridRow.textType),
              DataGridCell<String>(
                  columnName: 'Audio', value: dataGridRow.audioType),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              DataGridCell<int>(
                  columnName: 'LastUpdated', value: dataGridRow.committedTime),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  final box = Hive.box('appconfig');
  final AssessmentsController _assessmentsController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'LastUpdated') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Title') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {
                    var title = row
                        .getCells()
                        .where((element) => element.columnName == 'Title')
                        .first
                        .value;
                    // var type = row
                    //     .getCells()
                    //     .where((element) => element.columnName == 'Type')
                    //     .first
                    //     .value;
                    //               var username = row
                    // .getCells()
                    // .where((element) => element.columnName == 'Username')
                    // .first
                    // .value;
                    var status = row
                        .getCells()
                        .where((element) => element.columnName == 'Status')
                        .first
                        .value;
                    var questionRecordId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var userName = row
                        .getCells()
                        .where((element) => element.columnName == 'Username')
                        .first
                        .value;
                    var type = row
                        .getCells()
                        .where((element) => element.columnName == 'Type')
                        .first
                        .value;
                    if (type != Constants.AssessmentType_Running_Record) {
                      if (isTeacher) {
                        if (status == 'COMPLETED') {
                          _assessmentsController
                              .fetchAssessmentRecordGrading(questionRecordId);
                        }
                        _assessmentsController
                            .fetchAssessmentRecordInfoDetails(questionRecordId);
                        Get.to(() => EvaluationRecordReviewPage(), arguments: {
                          'title': title,
                          'status': status,
                          'recordId': questionRecordId,
                          'userName': userName,
                          'assessmentType': type
                        });
                        // Get.to(() => InAppWebViewTeacherQuzibookReviewScreen(
                        //     type: type,
                        //     username: username,
                        //     questionId: questionRecordId));
                      } else {
                        if (status == 'COMPLETED') {
                          _assessmentsController
                              .fetchAssessmentRecordGrading(questionRecordId);
                        }
                        _assessmentsController
                            .fetchAssessmentRecordInfoDetails(questionRecordId);
                        Get.to(() => EvaluationRecordReviewPage(), arguments: {
                          'title': title,
                          'status':
                              status == 'COMPLETED' ? 'COMPLETED' : 'UNDONE',
                          'assessmentType': type
                        });
                        // Get.to(() => InAppWebViewStudentQuizbookReviewScreen(
                        //     type: type,
                        //     username: username,
                        //     questionId: questionId)
                        //     );
                      }
                    }
                  },
                  child: Text(
                    dataGridCell.value,
                    style: TextStyle(
                        fontFamily: 'Noto Sans SC',
                        color: Colors.blue[300],
                        fontWeight: FontWeight.bold),
                    overflow: TextOverflow.fade,
                  ),
                ));
          }
          // if (GetPlatform.isMacOS || GetPlatform.isWeb) {
          //   return Container(
          //       alignment: Alignment.centerLeft,
          //       padding: EdgeInsets.symmetric(horizontal: 16.0),
          //       child: GestureDetector(
          //         onTap: () {},
          //         child: Text(
          //           dataGridCell.value,
          //           style: Get.textTheme.titleLarge,
          //           overflow: TextOverflow.ellipsis,
          //         ),
          //       ));
          // } else {
          //   return Container(
          //       alignment: Alignment.centerLeft,
          //       padding: EdgeInsets.symmetric(horizontal: 16.0),
          //       child: GestureDetector(
          //         onTap: () {
          //           var type = row
          //               .getCells()
          //               .where((element) => element.columnName == 'Type')
          //               .first
          //               .value;
          //           var username = row
          //               .getCells()
          //               .where((element) => element.columnName == 'Username')
          //               .first
          //               .value;
          //           var questionRecordId = row
          //               .getCells()
          //               .where((element) => element.columnName == 'Id')
          //               .first
          //               .value;
          //           if (isTeacher) {
          //             Get.to(() => InAppWebViewTeacherQuzibookReviewScreen(
          //                 type: type,
          //                 username: username,
          //                 questionId: questionRecordId));
          //           } else {
          //             _assessmentsController
          //                 .fetchAssessmentRecordInfoDetails(questionRecordId);
          //             Get.to(() => EvaluationRecordReviewPage());
          //             // Get.to(() => InAppWebViewStudentQuizbookReviewScreen(
          //             //     type: type,
          //             //     username: username,
          //             //     questionId: questionId)
          //             //     );
          //           }
          //         },
          //         child: Text(
          //           dataGridCell.value,
          //           style: TextStyle(
          //               color: Colors.blue[300], fontWeight: FontWeight.bold),
          //           overflow: TextOverflow.ellipsis,
          //         ),
          //       ));
          // }

          else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
